part of "../../time.dart";

/// 由于YYYY、YY的替换有冲突（比如YYYY可能会被识别为2个YY）
/// 因此必须要将他们放到同一个函数中，这样通过先后顺序来避免冲突
extension FormatExtension on String {
  /// 将YY、YYYY替换为年份
  String formatYear(int year) {
    var result = this;
    result = result.replaceAll(RegExp(r'YYYY'), year.toString());
    result = result.replaceAll(
        RegExp(r'YY'), (year % 100).toString().padLeft(2, '0'));

    return result;
  }

  /// 将M、MM替换为月份
  String formatMonth(int month) {
    var result = this;
    result = result.replaceAll(RegExp(r'MM'), month.toString().padLeft(2, '0'));
    result = result.replaceAll(RegExp(r'M'), month.toString());

    return result;
  }

  /// 将D、DD替换为日期
  String formatDay(int day) {
    var result = this;
    result = result.replaceAll(RegExp(r'DD'), day.toString().padLeft(2, '0'));
    result = result.replaceAll(RegExp(r'D'), day.toString());

    return result;
  }

  /// 将W、WW替换为周
  String formatWeekday(int weekday) {
    var result = this;

    late final String weekdayChinese;
    switch (weekday) {
      case 1:
        weekdayChinese = "一";
        break;
      case 2:
        weekdayChinese = "二";
        break;
      case 3:
        weekdayChinese = "三";
        break;
      case 4:
        weekdayChinese = "四";
        break;
      case 5:
        weekdayChinese = "五";
        break;
      case 6:
        weekdayChinese = "六";
        break;
      case 7:
        weekdayChinese = "日";
        break;
      default:
        throw UnimplementedError();
    }

    result = result.replaceAll(RegExp(r'WW'), weekdayChinese);
    result = result.replaceAll(RegExp(r'W'), weekday.toString());
    return result;
  }

  /// 将h、hh替换为小时数
  String formatHour(int hour) {
    var result = this;
    result = result.replaceAll(RegExp(r'hh'), hour.toString().padLeft(2, '0'));
    result = result.replaceAll(RegExp(r'h'), hour.toString());

    return result;
  }

  /// 将m、mm替换为分钟数
  String formatMinute(int minute) {
    var result = this;
    result =
        result.replaceAll(RegExp(r'mm'), minute.toString().padLeft(2, '0'));
    result = result.replaceAll(RegExp(r'm'), minute.toString());

    return result;
  }

  /// 将s、ss替换为秒数
  String formatSecond(int second) {
    var result = this;
    result =
        result.replaceAll(RegExp(r'ss'), second.toString().padLeft(2, '0'));
    result = result.replaceAll(RegExp(r's'), second.toString());

    return result;
  }
}
